#include "WebConfigManager.h"
#include <WiFi.h>
#include <SPIFFS.h>
#include <ESPmDNS.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "TCPManager.h"
AsyncWebServer server(80);

String serverIp = "47.100.2.86";
int serverPort = 5002;

//  根路径处理
void handleRoot(AsyncWebServerRequest *request)
{
String html = "<!DOCTYPE html>"
              "<html>"
              "<head>"
              "<meta charset='utf-8'>"
              "<title>ESP32 配置</title>"
              "<style>"
              "body { font-family: Arial, sans-serif; background: #f7f7f7; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }"
              ".container { background: #fff; padding: 20px; border-radius: 10px; box-shadow: 0 0 15px rgba(0,0,0,0.2); width: 400px; }"
              "h2 { text-align: center; color: #2c3e50; margin-bottom: 20px; }"
              "p { text-align: center; margin-bottom: 20px; }"
              "input[type='text'], input[type='number'] { width: 100%; padding: 8px; margin: 5px 0 15px; border: 1px solid #ccc; border-radius: 5px; box-sizing: border-box; }"
              ".buttons { display: flex; justify-content: space-between; }"
              "input[type='submit'], button { padding: 10px 20px; border: none; border-radius: 5px; background: #3498db; color: #fff; cursor: pointer; flex: 1; margin-right: 10px; }"
              "input[type='submit']:hover, button:hover { background: #2980b9; }"
              "button:last-child { margin-right: 0; }"
              "</style>"
              "</head>"
              "<body>"
              "<div class='container'>"
              "<h2>ESP32 配置页面</h2>"
              "<p>当前 WiFi IP：" + WiFi.localIP().toString() + "</p>"
              "<form action='/save' method='POST'>"
              "服务器 IP：<input type='text' name='ip' value='" + serverIp + "'>"
              "端口号：<input type='number' name='port' value='" + String(serverPort) + "'>"
              "<div class='buttons'>"
              "<input type='submit' value='保存配置'>"
              "<button type='submit' formmethod='post' formaction='/reboot'>重启设备</button>"
              "</div>"
              "</form>"
              "</div>"
              "</body>"
              "</html>";

    request->send(200, "text/html", html);
}

//  保存配置
void handleSave(AsyncWebServerRequest *request)
{
    if (request->hasParam("ip", true))
    {
        serverIp = request->getParam("ip", true)->value();
    }
    if (request->hasParam("port", true))
    {
        serverPort = request->getParam("port", true)->value().toInt();
    }

    File file = SPIFFS.open("/config.txt", "w");
    if (file)
    {
        file.println(serverIp);
        file.println(serverPort);
        file.close();
    }
    // 更新 TCPManager（覆盖默认值）
    TCPManager::TCP_HOST = serverIp;
    TCPManager::TCP_PORT = serverPort;

    String html = R"rawliteral(
        <html><body>
        <h3>配置已保存！</h3>
        <a href='/'>返回配置页</a>
        </body></html>
    )rawliteral";
    request->send(200, "text/html; charset=utf-8", html);
}

//  重启设备
void handleReboot(AsyncWebServerRequest *request)
{
    // 返回一个提示页面
    String html = R"rawliteral(
       <html><body>
       <h3>正在重启设备...</h3>
       <p>页面将在 2 秒后刷新</p>
       <script>
         setTimeout(function(){
           window.location.href = "/";
         }, 2000);
       </script>
       </body></html>
    )rawliteral";
    request->send(200, "text/html; charset=utf-8", html);

    // 延迟 2 秒再重启
    // 使用 Task 或计时器避免阻塞
    xTaskCreate([](void*){
        vTaskDelay(2000 / portTICK_PERIOD_MS);
        ESP.restart();
    }, "restartTask", 2048, NULL, 1, NULL);
}

namespace WebConfigManager
{

    void startServer()
    {
        if (!SPIFFS.begin(true))
        {
            Serial.println(" SPIFFS 启动失败！");
        }

        // 读取历史配置
        if (SPIFFS.exists("/config.txt"))
        {
            File file = SPIFFS.open("/config.txt", "r");
            TCPManager::TCP_HOST = file.readStringUntil('\n');
            TCPManager::TCP_HOST.trim();
            TCPManager::TCP_PORT = file.readStringUntil('\n').toInt();
            file.close();
        }

        //  绑定异步路由
        server.on("/", HTTP_GET, handleRoot);
        server.on("/save", HTTP_POST, handleSave);
        server.on("/reboot", HTTP_POST, handleReboot);

        //  启动服务器
        server.begin();
        Serial.println("Web 配置服务器已启动: http://" + WiFi.localIP().toString());

        // 启用 mDNS
        if (MDNS.begin("esp32"))
        {
            Serial.println("mDNS管理: http://esp32.local");
        }
        else
        {
            Serial.println("mDNS 启动失败");
        }
    }
}